package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 壮哥
 * @Date 2021/9/21/20:08
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDTO dto) {
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数异常");
        }
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName,dto.getName()));
        if (adUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        String password = adUser.getPassword();
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
        if (!inputPwd.equals(password)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }
        if (adUser.getStatus().equals(AdminConstants.USER_STATUS_ISSTATUS)){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"状态异常");
        }
        adUser.setLoginTime(new Date());
        updateById(adUser);
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(adUser,adUserVO);
        Map result=new HashMap<>();
        result.put("token",token);
        result.put("user",adUserVO);
        return ResponseResult.okResult(result);
    }
}
